package com.simple.datax.common.util;
import java.io.IOException;
import java.io.OutputStream;

public class ByteUtil {
	public static void main(String args[]) {
		String data = "hedfsfsfsdsfsdf";
		int rtn = ByteUtil.findBytes(data.getBytes(), 0, "he".getBytes());
		System.out.println(rtn);

	}

	public static int first_not_blank(byte[] source) {
		if (source == null) {
			return -1;
		}
		for (int i = 0; i < source.length; i++) {
			if (source[i] != " ".getBytes()[0]) {
				return i;
			}
		}
		return -1;
	}

	public static void write_without_xmlhead(OutputStream out, byte[] source)
			throws IOException {
		// 有些内部报文是以<?...?>开头，一般出自2.x版本的数据。
		// pem解析后出现这种情况
		int tag = ByteUtil.first_not_blank(source);
		if (tag == -1) {
			out.write(source);
		} else {
			// 看是不是以<?开头
			int tag1 = 0;
			tag1 = ByteUtil.findBytes(source, tag, "<?".getBytes());
			if (tag == tag1) {
				// 开头是<?
				tag = ByteUtil.findBytes(source, tag1, "?>".getBytes());
				if (tag != -1) {
					out.write(source, tag + 2, source.length - tag - 2);
				} else {
					out.write(source);
				}
			} else {// 开头不是<?
				out.write(source);
			}

		}
	}

	public static int findBytes(byte[] source, int startpos, byte[] bytes) {
		if (startpos < 0) {
			startpos = 0;
		}
		while (startpos <= source.length - bytes.length) {
			int j = 0;
			for (int i = startpos; j < bytes.length; i++, j++) {
				if (source[i] != bytes[j]) {
					startpos++;
					break;
				}
			}
			if (j == bytes.length) {
				return startpos;
			}
		}
		return -1;
	}

	public static int rfindBytes(byte[] source, int startpos, byte[] bytes) {
		if (startpos >= source.length) {
			startpos = source.length - 1;
		}
		while (startpos >= bytes.length - 1) {
			int j = bytes.length - 1;
			for (int i = startpos; j >= 0; i--, j--) {
				if (source[i] != bytes[j]) {
					startpos--;
					break;
				}
			}
			if (j == -1) {
				return startpos - bytes.length + 1;
			}
		}
		return -1;
	}
}
